package com.mysterymall.Service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mysterymall.Common.Comp.HttpStatus;
import com.mysterymall.Common.Comp.LocalCache;
import com.mysterymall.Common.Comp.OrderDelay;
import com.mysterymall.Common.Config.PaymentConfiguration;
import com.mysterymall.Common.Utils.BaseEnum;
import com.mysterymall.Common.Utils.LogUtil;
import com.mysterymall.Common.Utils.Result;
import com.mysterymall.Mapper.*;
import com.mysterymall.Model.Dto.PlaceAnOrderCallbackDto;
import com.mysterymall.Model.Dto.WithdrawDepositQueryDto;
import com.mysterymall.Model.Entity.*;
import com.mysterymall.Service.PaymentService;
import com.mysterymall.Task.OrderDelayQueueJob;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.util.*;

/**
 * @ClassName com.mysterymall.Service.Impl
 * @Description
 * @Author HuangWX
 * @Time 2023/12/02  17:13
 */
@Service
@Slf4j
public class PaymentServiceImpl implements PaymentService {


    private final PaymentConfiguration paymentConfiguration;

    private final UserBlindBoxGroupMapper userBlindBoxGroupMapper;

    private final UserGoodsMapper userGoodsMapper;

    private final GameCurrencyDetailMapper gameCurrencyDetailMapper;

    private final PaymentDetailMapper paymentDetailMapper;

    private final OrderInfoMapper orderInfoMapper;

    private final UserMapper userMapper;

    private final TeamMapper teamMapper;

    private final BrokerageDetailMapper brokerageDetailMapper;


    private final WithdrawDepositMapper withdrawDepositMapper;

    private final BankCodeMapper bankCodeMapper;

    private final OperationRecordsMapper operationRecordsMapper;


    private final OrderDelayQueueJob orderDelayQueueJob;

    private static ThreadLocal<PrivateKey> privateKeyThreadLocal = new ThreadLocal<>();


    /**
     * 构造器注入
     *
     * @param paymentConfiguration     支付配置
     * @param userBlindBoxGroupMapper  盲盒组映射器
     * @param userGoodsMapper          商品组映射器
     * @param gameCurrencyDetailMapper 游戏组映射器
     * @param paymentDetailMapper      支付明细映射器
     * @param orderInfoMapper          订单信息映射器
     * @param userMapper               用户映射器
     * @param teamMapper               团队映射器
     * @param brokerageDetailMapper    佣金明细映射器
     */
    public PaymentServiceImpl(PaymentConfiguration paymentConfiguration, UserBlindBoxGroupMapper userBlindBoxGroupMapper,
                              UserGoodsMapper userGoodsMapper, GameCurrencyDetailMapper gameCurrencyDetailMapper,
                              PaymentDetailMapper paymentDetailMapper, OrderInfoMapper orderInfoMapper,
                              UserMapper userMapper, TeamMapper teamMapper, BrokerageDetailMapper brokerageDetailMapper,
                              OrderDelayQueueJob orderDelayQueueJob, WithdrawDepositMapper withdrawDepositMapper,
                              BankCodeMapper bankCodeMapper,OperationRecordsMapper operationRecordsMapper) {
        this.paymentConfiguration = paymentConfiguration;
        this.userBlindBoxGroupMapper = userBlindBoxGroupMapper;
        this.userGoodsMapper = userGoodsMapper;
        this.gameCurrencyDetailMapper = gameCurrencyDetailMapper;
        this.paymentDetailMapper = paymentDetailMapper;
        this.orderInfoMapper = orderInfoMapper;
        this.userMapper = userMapper;
        this.teamMapper = teamMapper;
        this.brokerageDetailMapper = brokerageDetailMapper;
        this.orderDelayQueueJob = orderDelayQueueJob;
        this.withdrawDepositMapper = withdrawDepositMapper;
        this.bankCodeMapper = bankCodeMapper;
        this.operationRecordsMapper = operationRecordsMapper;
    }


    @Override
    @Transactional
    public Result placeAnOrder(OrderInfo orderInfo) throws Exception {

        // 盲盒类型
        String BoxType = BaseEnum.Goods_Type_Blind_Box_Group.getCode();

        // 商品类型
        String GoodsType = BaseEnum.Goods_Type_Goods_Attribute.getCode();

        // 充值类型
        String RechargeType = BaseEnum.Goods_Type_Game_Currency.getCode();

        // 参数集
        Map<String, String> params = new TreeMap<String, String>();

        // 商品实付金额
        params.put("amount", orderInfo.getGoodsAmount().toString());

        // 币种
        params.put("currency", paymentConfiguration.getCurrency());

        // 商户号
        params.put("merNo", paymentConfiguration.getMerNo());

        // 本地系统订单号
        params.put("merchantOrderNo", orderInfo.getId());

        // 支付编码
        params.put("payCode", paymentConfiguration.getPayCode()[0]);

        // 支付回调
        params.put("notifyUrl", paymentConfiguration.getNotifyUrl());

        // 商品名称
        String goodsName = "";

        // 商品名称
        if (orderInfo.getGoodsType().equals(BoxType)) {

            LambdaQueryWrapper<UserBlindBoxGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserBlindBoxGroup::getOrderInfoId, orderInfo.getId());
            List<UserBlindBoxGroup> userBlindBoxGroupList = userBlindBoxGroupMapper.selectList(lambdaQueryWrapper);

            // 未查询到下单盲盒或者数量不对
            if (userBlindBoxGroupList.isEmpty() || !orderInfo.getGoodsQuantity().equals(userBlindBoxGroupList.size())) {
                return new Result(HttpStatus.BAD_NOT_PASS, "message.orderCont.orderError");
            } else {
                goodsName = userBlindBoxGroupList.get(0).getGroupName().split("_")[1];
            }

        } else if (orderInfo.getGoodsType().equals(GoodsType)) {

            LambdaQueryWrapper<UserGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserGoods::getOrderInfoId, orderInfo.getId());
            UserGoods userGoods = userGoodsMapper.selectOne(lambdaQueryWrapper);

            // 未下单商品
            if (userGoods == null) {
                return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
            } else {
                goodsName = userGoods.getGoodsName().split("_")[1];
            }

        } else if (orderInfo.getGoodsType().equals(RechargeType)) {

            LambdaQueryWrapper<PaymentDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PaymentDetail::getOrderId, orderInfo.getId());
            PaymentDetail paymentDetail = paymentDetailMapper.selectOne(lambdaQueryWrapper);

            // 未下单充值
            if (paymentDetail == null) {
                return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
            } else {
                goodsName = "Game Currency";
            }

        }

        // 写入商品名称(英文)
        params.put("goodsName", goodsName);

        String sign = getSign(params);

        // 签名
        params.put("sign", sign);

        // 保存签名值
        orderInfoMapper.updateById(orderInfo);

        // 请求
        String responseBody = this.httpControls(params, paymentConfiguration.getPlaceAnOrderUrl());

        JSONObject jsonObject = JSONObject.parseObject(responseBody);

        String paymentUrl = "";
        try {
            if ("SUCCESS".equals(jsonObject.get("code"))) {
                paymentUrl = (String) jsonObject.get("payLink");
                String orderId = orderInfo.getId();
                Map<String, Object> map = new HashMap<>();
                map.put("orderId", orderId);
                map.put("paymentUrl", paymentUrl);

                OrderDelayQueueJob.delayQueue.put(new OrderDelay(orderId, new Date().getTime()));

                return new Result(HttpStatus.SUCCESS, "message.querySuccess", map);
            } else {
                return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Map<String, Object> withdrawDeposit(WithdrawDeposit withdrawDeposit) {


        Map<String, Object> map = new HashMap<>();


        // 参数集
        Map<String, String> params = new TreeMap<String, String>();

        // 商品实付金额
        params.put("merNo", paymentConfiguration.getMerNo());

        // 本地系统订单号
        params.put("merchantOrderNo", withdrawDeposit.getId());

        // 币种
        params.put("currency", paymentConfiguration.getCurrency());

        // 金额
        params.put("amount", withdrawDeposit.getWithdrawAmount().toString());

        // 收款人姓名
        params.put("customerName", withdrawDeposit.getBeneficiaryName());

        // 收款人银行账号
        params.put("customerAccount", withdrawDeposit.getBankAccountNumber());

        // 查询银行编码
        LambdaQueryWrapper<BankCode> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BankCode::getBankName, withdrawDeposit.getBankName());
        BankCode bankCode = bankCodeMapper.selectOne(lambdaQueryWrapper);

        if(bankCode == null){
            map.put("Result", new Result(HttpStatus.BAD_NOT_PASS, "message.bankCodeError"));
            return map;
        }

        params.put("bankCode", withdrawDeposit.getBankName());

        // 签名
        String sign = getSign(params);

        // 签名
        params.put("sign", sign);

        // 请求
        String responseBody = this.httpControls(params, paymentConfiguration.getWithdrawDepositUrl());

        System.out.println(responseBody);

        JSONObject jsonObject = JSONObject.parseObject(responseBody);

        try {
            if ("SUCCESS".equals(jsonObject.get("code"))) {
                OperationRecords operationRecords = new OperationRecords();
                operationRecords.setUserId(StpUtil.getLoginIdAsString());
                User user = userMapper.selectById(withdrawDeposit.getUserId());
                operationRecords.setContent("同意了用户" + user.getUserName() + " 金额为: " + withdrawDeposit.getWithdrawAmount() +"的提现申请");
                operationRecordsMapper.insert(operationRecords);
                return map;
            } else {
                map.put("Result", new Result(HttpStatus.BAD_NOT_PASS, "message.queryError-" + jsonObject.get("msg")));
                return map;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    @Transactional
    public String placeAnOrderCallback(PlaceAnOrderCallbackDto placeAnOrderCallbackDto) throws Exception {

        // 验签
        if (this.verifySign(placeAnOrderCallbackDto)) {
            OrderInfo orderInfo = orderInfoMapper.selectById(placeAnOrderCallbackDto.getMerchantOrderNo());
            // 支付状态 和本地订单查询
            if ("1".equals(placeAnOrderCallbackDto.getResult()) && orderInfo != null) {
                // 支付金额验证
                if (orderInfo.getGoodsAmount().compareTo(new BigDecimal(placeAnOrderCallbackDto.getAmount())) == 0) {
                    if (orderInfo.getOrderStatus().equals(BaseEnum.Pending_Payment.getCode())) {
                        this.paymentSuccess(orderInfo);
                        return "SUCCESS";
                    }
                }
            }
        }
        return "ERROR";
    }

    @Override
    public Result getPaymentResult(String orderId) {

        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);

        if (orderInfo == null) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        // 查询是否是自己的订单
        if (!orderInfo.getCreateUser().equals(StpUtil.getLoginIdAsString())) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        // 查询订单状态
        if (orderInfo.getOrderStatus().equals(BaseEnum.Payment_Success.getCode())) {
            return new Result(HttpStatus.SUCCESS, "message.querySuccess", "SUCCESS");
        }
        return new Result(HttpStatus.SUCCESS, "message.querySuccess", "WAIT");
    }


    @Override
    @Transactional
    public Result luckyCoinPayment(OrderInfo orderInfo) {

        // 用户
        User user = userMapper.selectById(StpUtil.getLoginId().toString());

        // 判断用户剩余金额是否可以支付
        if (user.getAmount().compareTo(orderInfo.getGoodsAmount()) >= 0) {

            user.setAmount(user.getAmount().subtract(orderInfo.getGoodsAmount()));

            userMapper.updateById(user);

            // 支付明细表
            GameCurrencyDetail gameCurrencyDetail = new GameCurrencyDetail();

            // 用户ID
            gameCurrencyDetail.setUserId(user.getId());

            // 类型-- 支出
            gameCurrencyDetail.setType(BaseEnum.Game_Currency_Disburse.getCode());

            // 商品名称
            gameCurrencyDetail.setGoodsName(orderInfo.getLogisticsCode());

            // 金额
            gameCurrencyDetail.setAmount(orderInfo.getGoodsAmount());

            orderInfo.setLogisticsCode("");

            orderInfoMapper.updateById(orderInfo);

            // 盲盒类型
            if (orderInfo.getGoodsType().equals(BaseEnum.Goods_Type_Blind_Box_Group.getCode())) {
                gameCurrencyDetail.setAmountType(BaseEnum.Game_Currency_Type_Buy_Blind_Box.getCode());

                // 商品类型
            } else if (orderInfo.getGoodsType().equals(BaseEnum.Goods_Type_Goods_Attribute.getCode())) {
                gameCurrencyDetail.setAmountType(BaseEnum.Game_Currency_Type_Buy_Goods.getCode());
            }
            gameCurrencyDetailMapper.insert(gameCurrencyDetail);

            this.paymentSuccess(orderInfo);

            return new Result(HttpStatus.SUCCESS, "message.paymentSuccess", orderInfo.getId());

        } else {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.notAmountError");
        }
    }

    @Override
    public Result withdrawDepositCallback(WithdrawDeposit withdrawDeposit) {

        // 查询提现

        return null;
    }

    @Override
    public WithdrawDepositQueryDto withdrawDepositQuery(WithdrawDeposit withdrawDeposit) {

        WithdrawDeposit withdrawDeposit1 = withdrawDepositMapper.selectById(withdrawDeposit.getId());

        if (withdrawDeposit1 == null) {
            return null;
        }

        // 参数集
        Map<String, String> params = new TreeMap<String, String>();

        // 商户号
        params.put("merNo", paymentConfiguration.getMerNo());

        // 本地系统订单号
        params.put("merchantOrderNo", withdrawDeposit.getId());

        // 签名
        String sign = getSign(params);

        // 签名
        params.put("sign", sign);

        // 请求
        String responseBody = this.httpControls(params, paymentConfiguration.getWithdrawDepositQueryUrl());

        JSONObject jsonObject = JSONObject.parseObject(responseBody);

        WithdrawDepositQueryDto withdrawDepositQueryDto = new WithdrawDepositQueryDto();

        withdrawDepositQueryDto = SetWithdrawDepositQueryDto(jsonObject);

        try {
            if(!"SUCCESS".equals((String) jsonObject.get("code"))){
                withdrawDepositQueryDto.setFailMsg((String) jsonObject.get("failMsg"));
            }
            if(!withdrawDeposit.getId().equals(withdrawDepositQueryDto.getMerchantOrderNo())){
                return null;
            }
            // 验签
            return verifySign(withdrawDepositQueryDto) ? withdrawDepositQueryDto : null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private WithdrawDepositQueryDto SetWithdrawDepositQueryDto(JSONObject jsonObject) {
        WithdrawDepositQueryDto withdrawDepositQueryDto = new WithdrawDepositQueryDto();
        withdrawDepositQueryDto.setCode((String) jsonObject.get("code"));
        withdrawDepositQueryDto.setMsg((String) jsonObject.get("msg"));
        withdrawDepositQueryDto.setMchNo((String) jsonObject.get("mchNo"));
        withdrawDepositQueryDto.setMerchantOrderNo((String) jsonObject.get("merchantOrderNo"));
        withdrawDepositQueryDto.setPtOrderNo((String) jsonObject.get("ptOrderNo"));
        withdrawDepositQueryDto.setAmount((BigDecimal) jsonObject.get("amount"));
        withdrawDepositQueryDto.setResult((Integer) jsonObject.get("result"));
        withdrawDepositQueryDto.setSign((String) jsonObject.get("sign"));
        return withdrawDepositQueryDto;
    }

    @Transactional
    public void paymentSuccess(OrderInfo orderInfo) {

        // 修改订单状态为已支付
        orderInfo.setOrderStatus(BaseEnum.Payment_Success.getCode());

        orderInfoMapper.updateById(orderInfo);

        LogUtil.info("支付成功: " + "\n" +
                "订单号:" + orderInfo.getId() + "\n" +
                "订单状态:" + orderInfo.getOrderStatus() + "\n" +
                "支付金额:" + orderInfo.getGoodsAmount() + "\n" +
                "支付类型:" + orderInfo.getGoodsType() + "\n" +
                "支付用户:" + orderInfo.getCreateUser());

        // 盲盒类型
        String BoxType = BaseEnum.Goods_Type_Blind_Box_Group.getCode();

        // 商品类型
        String GoodsType = BaseEnum.Goods_Type_Goods_Attribute.getCode();

        // 充值类型
        String RechargeType = BaseEnum.Goods_Type_Game_Currency.getCode();

        // 盲盒
        if (orderInfo.getGoodsType().equals(BoxType)) {

            LambdaQueryWrapper<UserBlindBoxGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserBlindBoxGroup::getOrderInfoId, orderInfo.getId());
            List<UserBlindBoxGroup> userBlindBoxGroupList = userBlindBoxGroupMapper.selectList(lambdaQueryWrapper);
            // 未下单盲盒或下单数量不对
            if (userBlindBoxGroupList.isEmpty() || !orderInfo.getGoodsQuantity().equals(userBlindBoxGroupList.size())) {
                LogUtil.error("支付成功后未查询到盲盒或者盲盒数量不对: " + "\n" +
                        "订单号:" + orderInfo.getId() + "\n" +
                        "盲盒数量:" + orderInfo.getGoodsQuantity() + "\n" +
                        "查询到的数量:" + userBlindBoxGroupList.size());
                // 修改订单状态为已支付异常
                orderInfo.setOrderStatus(BaseEnum.Abnormal.getCode());
                // 保存状态
                orderInfoMapper.updateById(orderInfo);
            } else {
                for (UserBlindBoxGroup userBlindBoxGroup : userBlindBoxGroupList) {
                    // 修改盲盒状态为不删除(展示)
                    userBlindBoxGroup.setIsDelete(BaseEnum.Not_Delete.getCode());
                    // 保存状态
                    userBlindBoxGroupMapper.updateById(userBlindBoxGroup);
                }
            }

            // 计算佣金
            this.computeCommissionControls(orderInfo);

            // 商品
        } else if (orderInfo.getGoodsType().equals(GoodsType)) {

            LambdaQueryWrapper<UserGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserGoods::getOrderInfoId, orderInfo.getId());
            List<UserGoods> userGoodsList = userGoodsMapper.selectList(lambdaQueryWrapper);

            // 未下单商品
            if (userGoodsList == null || userGoodsList.isEmpty()) {
                LogUtil.error("支付成功后未查询到商品: " + "\n" +
                        "订单号:" + orderInfo.getId());
                // 修改订单状态为已支付异常
                orderInfo.setOrderStatus(BaseEnum.Abnormal.getCode());
                // 保存状态
                orderInfoMapper.updateById(orderInfo);
            } else {
                for (UserGoods userGoods : userGoodsList) {
                    // 修改商品状态为不删除(展示)
                    userGoods.setDeleteIsStatus(BaseEnum.Not_Delete.getCode());
                    // 保存状态
                    userGoodsMapper.updateById(userGoods);
                }

                // 计算佣金
                this.computeCommissionControls(orderInfo);

            }
            // 游戏币充值
        } else if (orderInfo.getGoodsType().equals(RechargeType)) {

            LambdaQueryWrapper<PaymentDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PaymentDetail::getOrderId, orderInfo.getId());
            PaymentDetail paymentDetail = paymentDetailMapper.selectOne(lambdaQueryWrapper);

            // 未下单充值
            if (paymentDetail == null) {
                LogUtil.error("支付成功后未查询到充值: " + "\n" +
                        "订单号:" + orderInfo.getId());
                // 修改订单状态为已支付异常
                orderInfo.setOrderStatus(BaseEnum.Abnormal.getCode());
                // 保存状态
                orderInfoMapper.updateById(orderInfo);
            } else {

                // 修改展示状态为展示(不删除)
                paymentDetail.setPaymentStatus(BaseEnum.Not_Delete.getCode());

                // 保存状态
                paymentDetailMapper.updateById(paymentDetail);

                GameCurrencyDetail gameCurrencyDetail = new GameCurrencyDetail();

                // 下单用户
                gameCurrencyDetail.setUserId(orderInfo.getCreateUser());

                // 类型-- 收入
                gameCurrencyDetail.setType(BaseEnum.Game_Currency_Income.getCode());

                gameCurrencyDetail.setAmount(orderInfo.getGoodsAmount());

                gameCurrencyDetail.setGoodsName("Game Currency");

                gameCurrencyDetailMapper.insert(gameCurrencyDetail);

                User user = userMapper.selectById(orderInfo.getCreateUser());

                user.setAmount(user.getAmount().add(orderInfo.getGoodsAmount()));

                userMapper.updateById(user);
            }
        }

    }

    /**
     * 获取签名
     *
     * @param params json对象
     * @return String
     */
    public String getSign(Map<String, String> params) {

        // 商户密钥
        String merKey = paymentConfiguration.getMerKey();

        // 使用TreeMap来按照键的自然顺序排序
        TreeMap<String, String> sortedParams = new TreeMap<>(params);
        // 构建待签名字符串
        StringBuilder sbf = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                sbf.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        String signStr = sbf.toString();
        if (signStr.endsWith("&")) {
            signStr = signStr.substring(0, signStr.length() - 1);
        }
        // 加入密钥
        signStr = signStr + "&key=" + merKey;

        // 打印签名
        LogUtil.info("签名字符串: " + signStr);

        // 得到签名值
        return MD5(signStr).toLowerCase();
    }

    private static String MD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());

            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private String httpControls(Map<String, String> params, String url) {


        String sign = params.get("sign");

        // 保存支付签名
        LocalCache.CACHE.put(BaseEnum.Payment_Sign.getCode() + params.get("merchantOrderNo"), sign);


        OkHttpClient client = new OkHttpClient();

        // 构建请求体
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            formBodyBuilder.add(entry.getKey(), entry.getValue());
        }
        RequestBody requestBody = formBodyBuilder.build();

        // 构建 POST 请求
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                .build();

        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseBody = null;
                if (response.body() != null) {
                    responseBody = response.body().string();
                }
                System.out.println("Response: " + responseBody);
                return responseBody;
            } else {
                System.err.println("Request failed. Code: " + response.code() + ", Message: " + response.message());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }


    private boolean verifySign(PlaceAnOrderCallbackDto placeAnOrderCallbackDto){

        // 验签
        TreeMap<String, String> sortedParams = new TreeMap<>();

        sortedParams.put("mchNo", placeAnOrderCallbackDto.getMchNo());

        sortedParams.put("merchantOrderNo", placeAnOrderCallbackDto.getMerchantOrderNo());

        sortedParams.put("ptOrderNo", placeAnOrderCallbackDto.getPtOrderNo());

        sortedParams.put("amount", placeAnOrderCallbackDto.getAmount());

        sortedParams.put("result", placeAnOrderCallbackDto.getResult());

        String sign = getSign(sortedParams);

        return sign.equals(placeAnOrderCallbackDto.getSign());
    }


    private boolean verifySign(WithdrawDepositQueryDto withdrawDepositQueryDto){

        // 验签
        TreeMap<String, String> sortedParams = new TreeMap<>();

        sortedParams.put("code", withdrawDepositQueryDto.getCode());

        sortedParams.put("msg", withdrawDepositQueryDto.getMsg());

        sortedParams.put("mchNo", withdrawDepositQueryDto.getMchNo());

        sortedParams.put("merchantOrderNo", withdrawDepositQueryDto.getMerchantOrderNo());

        sortedParams.put("ptOrderNo", withdrawDepositQueryDto.getPtOrderNo());

        sortedParams.put("amount", withdrawDepositQueryDto.getAmount().toString());

        sortedParams.put("result", withdrawDepositQueryDto.getResult().toString());

        if (!"SUCCESS".equals(withdrawDepositQueryDto.getCode())) {
            sortedParams.put("failMsg", withdrawDepositQueryDto.getFailMsg());
        }

        return getSign(sortedParams).equals(withdrawDepositQueryDto.getSign());
    }


    @Transactional
    public void computeCommissionControls(OrderInfo orderInfo) {

        User user = userMapper.selectById(orderInfo.getCreateUser());

        LambdaQueryWrapper<Team> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();

        lambdaQueryWrapper1.eq(Team::getUserId, user.getId());

        Team team = teamMapper.selectOne(lambdaQueryWrapper1);

        // 存在上级才有佣金
        if (team != null) {

            BrokerageDetail brokerageDetail = new BrokerageDetail();

            brokerageDetail.setUserId(team.getUserId());

            brokerageDetail.setTeamId(team.getId());

            brokerageDetail.setScale(user.getScale());

            brokerageDetail.setOrderId(orderInfo.getId());

            BigDecimal commission = orderInfo.getGoodsAmount().multiply(user.getScale());

            commission = commission.setScale(2, RoundingMode.HALF_UP);


            User teamCreateUser = userMapper.selectById(team.getCreateUser());

            //  增加用户佣金
            teamCreateUser.setBrokerage(teamCreateUser.getBrokerage().add(commission));

            //  更新累计佣金
            team.setAccumulateAmount(team.getAccumulateAmount().add(commission));

            teamMapper.updateById(team);

            userMapper.updateById(teamCreateUser);

            // 佣金
            brokerageDetail.setAmount(commission);

            brokerageDetailMapper.insert(brokerageDetail);
        }
    }
}
